package com.cc.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cc.entity.Emp;
import com.cc.service.EmpService;
import com.cc.service.impl.EmpServiceImpl;
import com.cc.util.Page;
import com.cc.util.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 33314
 * @version 1.0
 * @description: TODO
 * @date 2025/4/18 09:54
 */
@WebServlet("/empServlet")
@MultipartConfig(maxRequestSize = 1024 * 1024 * 2)
public class EmpServlet extends HttpServlet {
    private EmpService empService = new EmpServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置响应格式
        resp.setContentType("application/json;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
        String method = req.getParameter("method")==null?"list":req.getParameter("method");
        switch (method){
            case "list":
                list(req, resp);
                break;
                case "add":
                add(req, resp);
                break;
                case "delete":
                delete(req, resp);
                break;
                case "edit":
                edit(req, resp);
                break;
                case "getEmpById":
                getEmpById(req, resp);
                break;
                default:
                list(req, resp);
                break;
        }
    }

    private void edit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前端参数
        String empId = req.getParameter("empId");
        String empName = req.getParameter("empName");
        String deptId = req.getParameter("deptId");
        String position = req.getParameter("position");
        String startDate = req.getParameter("startDate");
        String phone = req.getParameter("phone");
        Part part = req.getPart("imgURL");
        String imgUrl= null;
        if (part != null && part.getSize() > 0) {
            String fileName = part.getSubmittedFileName();
            String uploadPath = getServletContext().getRealPath("/uploads");
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }
            imgUrl = uploadPath + File.separator + fileName;
            part.write(imgUrl);
        }
        int id;
        if(empId==null||empId.equals("")){
            id=0;
        }else {
            id = Integer.parseInt(empId);
        }
        Emp emp = new Emp(id, empName, Integer.parseInt(deptId), position, startDate, phone,imgUrl);
        boolean flag=empService.edit(emp);
        if (flag) {
            PrintWriter writer = resp.getWriter();
            writer.write(JSON.toJSONString(new Result(200, "员工修改成功")));
        } else {
            PrintWriter writer = resp.getWriter();
            writer.write(JSON.toJSONString(new Result(500, "员工修改失败")));
        }
    }

    /**
     * @description: TODO 分页展示
     * @author
     * @date
     * @version 1.0
     */
    public void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //当前页码
        String pageIndex=req.getParameter("pageIndex");
        //搜索用户名
        String empName = req.getParameter("empName");
        if (pageIndex==null){
            pageIndex = "1";
        }
        Page<Emp> empPage = new Page<>();
        empPage.setPageIndex(Integer.parseInt(pageIndex));
        empPage = empService.getEmp(empPage, empName);
        //转为Json格式 值为Null的属性返回""
        String json = JSON.toJSONString(empPage, SerializerFeature.WriteMapNullValue);
        resp.getWriter().write(json);
    }
    /**
     * @description: TODO 新增功能
     * @author
     * @date
     * @version 1.0
     */
    public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        req.setCharacterEncoding("utf-8");

        String method = req.getParameter("method");
        if ("add".equals(method)) {
            Emp emp = new Emp();
            emp.setEmpName(req.getParameter("emp_name"));
            System.out.println("empName:" + req.getParameter("emp_name"));
            emp.setDeptId(Integer.parseInt(req.getParameter("dep_name")));
            emp.setPosition(req.getParameter("position"));
            emp.setStartDate(req.getParameter("start_date"));
            emp.setPhone(req.getParameter("phone"));
            Part part = req.getPart("imgURL");
            Emp emp2 = new Emp(0, emp.getEmpName(), emp.getDeptId(), emp.getDeptName(), emp.getPosition(), emp.getStartDate(), emp.getPhone(), emp.getImgUrl());
            if (part != null && part.getSize() > 0) {
                String fileName = part.getSubmittedFileName();
                String uploadPath = getServletContext().getRealPath("/uploads");
                File uploadDir = new File(uploadPath);
                if (!uploadDir.exists()) {
                    uploadDir.mkdir();
                }
                String filePath = uploadPath + File.separator + fileName;
                part.write(filePath);
                emp.setImgUrl("/uploads/" + fileName); // 设置 imgUrl
            }

            boolean result = empService.addEmp(emp);

            PrintWriter writer = resp.getWriter();
            if (result) {
                writer.write(JSON.toJSONString(new Result(200, "员工添加成功")));
            } else {
                writer.write(JSON.toJSONString(new Result(500, "员工添加失败")));
            }
            writer.flush();
            writer.close();
        }
    }

    /**
     * @description: 删除功能
     * @author
     * @date
     * @version 1.0
     */
    public void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取员工ID
        String empId = req.getParameter("empId");

        // 校验 empId 是否为空
        if (empId == null || empId.trim().isEmpty()) {
            resp.getWriter().write(JSON.toJSONString(new Result(400, "员工ID不能为空")));
            return;
        }

        // 将 empId 转换为整数
        int id = Integer.parseInt(empId);

        // 调用服务层删除员工信息
        boolean flag = empService.deleteEmp(id);

        // 返回结果
        PrintWriter writer = resp.getWriter();
        if (flag) {
            writer.write(JSON.toJSONString(new Result(200, "员工删除成功")));
        } else {
            writer.write(JSON.toJSONString(new Result(500, "员工删除失败")));
        }
        writer.flush();
        writer.close();
    }



    /**
     * @description: TODO 修改功能
     * @author
     * @date
     * @version 1.0
     */
    public void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Emp emp = new Emp();
        emp.setId(Integer.parseInt(req.getParameter("id")));
        emp.setEmpName(req.getParameter("emp_name"));
        emp.setDeptId(Integer.parseInt(req.getParameter("dept_id")));
        emp.setPosition(req.getParameter("position"));
        emp.setStartDate(req.getParameter("start_date"));
        emp.setPhone(req.getParameter("phone"));
        Part part = req.getPart("img_url");
        //上传文件
        if (part != null && part.getSize() > 0) {
            String fileName = part.getSubmittedFileName();
            String uploadPath = getServletContext().getRealPath("/uploads");
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }
            String filePath = uploadPath + File.separator + fileName;
            part.write(filePath);
            emp.setImgUrl("/uploads/" + fileName); // 设置 imgUrl
        }
        boolean b = empService.updateEmp(emp);
        PrintWriter writer = resp.getWriter();
        writer.write(JSON.toJSONString(b));
        writer.flush();
        writer.close();
    }

    public void getEmpById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("empId"));
        Emp emp = empService.getEmpById(id);
        PrintWriter writer = resp.getWriter();
        // 使用 JSON.toJSONStringWithDateFormat 方法格式化日期
        String json = JSON.toJSONStringWithDateFormat(emp, "yyyy-MM-dd", SerializerFeature.WriteMapNullValue);
        writer.write(json);
        writer.flush();
        writer.close();
    }
}
